<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购单号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择支付类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_pay_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_purchase_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="successFlag"
          @click="handleUpdate"
          v-hasPermi="['wms:purchaseOrder:success']"
        >生产完成</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="handelTableIsSelect"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="支付类型">
              <dict-tag :options="dict.type.wms_pay_type" :value="props.row.payType"/>
            </el-form-item>
            <el-row :gutter="10" v-if="props.row.payType === '1'">
              <el-col :span="12">
                <el-form-item label="先款比例">
                  <span>{{ props.row.prefixPayRate }}</span>
                  <span style="margin-left: 10px">备注：{{props.row.prefixRemark}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="进度款比例">
                  <span>{{ props.row.processPayRate }}</span>
                  <span style="margin-left: 10px">备注：{{props.row.processRemark}}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="props.row.payType === '1'">
              <el-col :span="12">
                <el-form-item label="尾款比例">
                  <span>{{ props.row.tailPayRate }}</span>
                  <span style="margin-left: 10px">备注：{{props.row.tailRemark}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="尾款支付时间">
                  <span>货到后{{ props.row.tailPayTime }}天付款</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="采购金额">
                  <span>{{ props.row.purchasePrice }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已支付金额">
                  <span>{{ props.row.payPrice }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="采购单号" align="center" prop="orderCode">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleLook(scope.row)">{{ scope.row.orderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="合同编码" align="center" prop="contractCode" />
      <el-table-column label="联系人" align="center" prop="nickName" />
      <el-table-column label="生产完成率" align="center" prop="successRate" />
      <el-table-column label="发货率" align="center" prop="fhRate" />
      <el-table-column label="完成率" align="center" prop="rate" />
      <el-table-column label="联系人" align="center" prop="nickName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_purchase_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 采购单生产完成对话框 -->
    <el-dialog :title="title" :visible.sync="openSuccess" width="80%" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="采购单号">
          {{orderCodeStr}}
        </el-form-item>
        <h1>商品信息</h1>
        <el-table :data="successProductTable" @selection-change="handleContractSelectionChange">
          <el-table-column align="center" type="selection" width="50" :selectable="handelSuccessProductIsSelect"/>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="商品编码">
                      <span>{{ props.row.productCode }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="商品类型">
                      <span>{{ props.row.productTypeName }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="计数单位">
                      <span>{{ props.row.unitName }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="尺寸单位">
                      <span>{{ props.row.ccUnitName }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="尺寸">
                      <span v-if="props.row.longWith || props.row.weight || props.row.height">{{ props.row.longWith + '*' + props.row.weight + '*' + props.row.height }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="重量">
                      <span>{{ props.row.zl }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="交货期（厂家）">
                      <span>{{ props.row.manufacturerDelivery }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="交货期（买家）">
                      <span>{{ props.row.delivery }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="详情">
                  <span>{{ props.row.detail }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
          <el-table-column label="商品型号" align="center" prop="modal" :show-overflow-tooltip="true"/>
          <el-table-column label="生产厂家" align="center" prop="scPurchaseCompanyName" :show-overflow-tooltip="true"/>
          <el-table-column label="商品数量" align="center" prop="productNum"/>
          <el-table-column label="成本" align="center" prop="oldOnlyPrice"/>
          <el-table-column label="单价" align="center" prop="onlyPrice"/>
          <el-table-column label="总价" align="center" prop="allPrice"/>
          <el-table-column label="状态" align="center" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_order_product_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSuccessForm" v-loading="btnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 采购详情对话框 -->
    <el-dialog title="采购详情" :visible.sync="openLook" width="80%" append-to-body>
      <el-form>
        <el-form-item label="采购单号" >
          {{orderCode}}
        </el-form-item>

        <el-form-item label="合同附件" v-if="fileList.length > 0">
          <el-upload
            action=""
            class="upload-demo"
            :disabled="true"
            :on-preview="handlePreview"
            :file-list="fileList">
          </el-upload>
        </el-form-item>

        <el-form-item label="支付附件" v-if="payFileList.length > 0">
          <el-upload
            action=""
            class="upload-demo"
            :disabled="true"
            :on-preview="handlePreview"
            :file-list="payFileList">
          </el-upload>
        </el-form-item>
      </el-form>
      <h1>商品信息</h1>
      <el-table :data="orderProductTable">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="商品编码">
                    <span>{{ props.row.productCode }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品类型">
                    <span>{{ props.row.productTypeName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="计数单位">
                    <span>{{ props.row.unitName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="尺寸单位">
                    <span>{{ props.row.ccUnitName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="尺寸">
                    <span v-if="props.row.longWith || props.row.weight || props.row.height">{{ props.row.longWith + '*' + props.row.weight + '*' + props.row.height }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="重量">
                    <span>{{ props.row.zl }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="交货期（厂家）">
                    <span>{{ props.row.manufacturerDelivery }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="交货期（买家）">
                    <span>{{ props.row.delivery }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="详情">
                <span>{{ props.row.detail }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
        <el-table-column label="商品型号" align="center" prop="modal" :show-overflow-tooltip="true"/>
        <el-table-column label="生产厂家" align="center" prop="scPurchaseCompanyName"/>
        <el-table-column label="商品数量" align="center" prop="productNum"/>
        <el-table-column label="成本" align="center" prop="oldOnlyPrice"/>
        <el-table-column label="单价" align="center" prop="onlyPrice"/>
        <el-table-column label="总价" align="center" prop="allPrice"/>
        <el-table-column label="状态" align="center" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.wms_order_product_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPurchaseOrder,
  getPurchaseOrder,
  updatePurchaseOrder,
  getSendProduct, sendPurchaseOrder, getPurchaseOrderInfo
} from "@/api/wms/purchaseOrder";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listTermsXlk} from "@/api/wms/terms";
import {logisticsUserListXlk} from "@/api/system/user";
import {listCityTree} from "@/api/wms/city";
import {listEntXlk} from "@/api/wms/ent";
import {getToken} from "@/utils/auth";

export default {
  name: "PurchaseOrder",
  components: {Treeselect},
  dicts: ['wms_purchase_status', 'wms_pay_type','wms_order_product_status', 'wms_logistics'],
  data() {
    let checkPayRate =(rule, value, callback) =>{
      let curRate = parseFloat(this.formLogistics.prefixPayRate) + parseFloat(this.formLogistics.processPayRate)
        + parseFloat(this.formLogistics.tailPayRate)
      if (curRate > 1) {
        return callback(new Error('先款进度款尾款总额不能大于1'));
      } else {
        callback()
      }
    }
    return {
      checkPayRate: checkPayRate,
      prefix: process.env.VUE_APP_BASE_API,
      // 附件参数
      uploadAccessory: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wms/logisticsOrder/uploadPic"
      },
      //按钮加载
      btnLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 生产完成禁用
      successFlag: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单管理表格数据
      purchaseOrderList: [],
      // 订单商品
      orderProductTable: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看详情
      openLook: false,
      // 生产完成弹出层
      openSuccess: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        contractCode: null,
        payType: null,
        status: null
      },
      orderCode: '',
      // 合同附件
      fileList: [],
      // 支付附件
      payFileList: [],
      // 箱体照片
      picList: [],
      // 生产完成商品列表
      successProductTable: [],
      // 发货商品列表
      purchaseProductTable: [],
      // 选择的商品列表
      selectedProducts: [],
      // 采购单编号
      orderCodeStr: '',
      // 物流对象
      formLogistics: {},
      // 物流验证
      rulesLogistics: {
        prefixPayRate: [
          { required: true, message: "先款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '先款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:checkPayRate, trigger: 'blur' }
        ],
        processPayRate: [
          { required: true, message: "进度款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '进度款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:checkPayRate, trigger: 'blur' }
        ],
        tailPayRate: [
          { required: true, message: "尾款不可为空", trigger: "blur"},
          { pattern: /^(1|(0(\.\d)?))$/, message: '尾款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:checkPayRate, trigger: 'blur'}
        ],
        tailPayTime: [
          { required: true, message: "尾款支付时间不可为空", trigger: "blur" },
          { pattern: /^([0|[1-9]{1,3})$/, message: '尾款支付时间只能是整数最大999', trigger: 'blur' }
        ],
        logisticsPrice: [
          { required: true, message: "运费不可为空", trigger: "blur" },
          { pattern: /^(0|[1-9])\d{0,8}(\.\d{1,2})?$/, message: '运费只能是数值最大9位整数2位小数', trigger: 'blur' }
        ],
        payPrice: [
          { required: true, message: "支付金额不可为空", trigger: "blur" },
          { pattern: /^(0|[1-9])\d{0,8}(\.\d{1,2})?$/, message: '支付金额只能是数值最大9位整数2位小数', trigger: 'blur' }
        ],
        logisticsTermsId: [
          { required: true, message: "物流条款不可为空", trigger: "blur" }
        ],
        sendAddressId: [
          { required: true, message: "发货城市不可为空", trigger: "blur" }
        ],
        deliveryAddressId: [
          { required: true, message: "收货城市不可为空", trigger: "blur" }
        ],
        sendAddress: [
          { max: 255, message: '发货城市长度最多 255个字', trigger: 'blur' }
        ],
        deliveryAddress: [
          { max: 255, message: '收货城市长度最多 255个字', trigger: 'blur' }
        ],
        boxCode: [
          { max: 50, message: '箱体编号长度最多 50个字', trigger: 'blur' }
        ],
        goodsArrivedTime: [
          { required: true, message: "预计到货日期不可为空", trigger: "blur" }
        ],
        qgEntId: [
          { required: true, message: "清关公司不可为空", trigger: "blur" }
        ],
        logisticsNo: [
          { required: true, message: "货运单号不可为空", trigger: "blur" },
          { max: 50, message: '货运单号长度最多 50个字', trigger: 'blur' }
        ]
      },
      // 物流条款集合
      termList: [],
      // 联系人集合
      userList: [],
      pickerOptions: {
        disabledDate(time) {
          //时间选择框必须大于今天
          return time.getTime() < Date.now() - 8.64e7;
          // 或者 return time.getTime() < Date.now();
        }
      },
      // 城市树列表
      cityOptions: [],
      // 清关公司列表
      entOptions: [],
      // 箱体照片
      accessoryList: [],
      // 合同附件
      contractAccessoryList: [],
      // 支付附件
      payAccessoryList: []
    };
  },
  created() {
    this.getList();
    this.getTermList();
    this.getLogisticsUserList();
    this.getCity();
    this.getEntList();
  },
  methods: {
    /** 查询采购单管理列表 */
    getList() {
      this.loading = true;
      listPurchaseOrder(this.queryParams).then(response => {
        this.purchaseOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询条款列表 */
    getTermList() {
      listTermsXlk().then(response => {
        this.termList = response.data;
      });
    },
    /** 查询联系人下拉框 */
    getLogisticsUserList() {
      logisticsUserListXlk().then(response => {
        this.userList = response.data;
      });
    },
    // 查询城市树
    getCity(){
      listCityTree().then(response => {
        this.cityOptions = response.data;
      })
    },
    /** 查询清关公司列表 */
    getEntList() {
      listEntXlk({entType: '2', gysType: '0'}).then(response => {
        this.entOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSuccess = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.orderCodeStr = ''
      this.selectedProducts = []
      this.successProductTable = []
      this.purchaseProductTable = []
      this.accessoryList = []
      this.contractAccessoryList = []
      this.payAccessoryList = []
      this.fileList = []
      this.payFileList = []
      this.picList = []
      this.formLogistics = {
        purchaseCode: null,
        contractCode: null,
        productNum: 0,
        payType: '1',
        logisticsPrice: null,
        logisticsTermsId: null,
        logisticsTerms: null,
        logisticsModule: '0',
        logisticsNo: null,
        consigneeIdArr: [],
        consigneeId: null,
        sendAddressId: null,
        deliveryAddressId: null,
        sendAddress: null,
        deliveryAddress: null,
        boxCode: null,
        goodsArrivedTime: null,
        prefixPayRate: 0,
        processPayRate: 0,
        tailPayRate: 0,
        qgEntId: null,
        tailPayTime: 0,
        payPrice: 0
      };
      this.resetForm("formLogistics");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderCode)
      this.successFlag = true
      selection.forEach(item => {
        let suc = item.successRate.split('/')
        if (parseInt(suc[0]) < parseInt(suc[1])) {
          this.successFlag = false
        }
      })
    },
    /** 生产完成按钮操作 */
    handleUpdate() {
      this.reset();
      const orderCode = this.ids
      this.orderCodeStr = orderCode.join(',')
      getPurchaseOrder(orderCode).then(response => {
        let data = response.data;
        this.successProductTable = data.products;
        this.openSuccess = true;
        this.title = "采购单生产完成";
      });
    },
    /** 提交生产完成按钮 */
    submitSuccessForm() {
      if (this.selectedProducts.length > 0) {
        this.btnLoading = true
          updatePurchaseOrder({products: this.selectedProducts}).then(response => {
            this.$modal.msgSuccess("提交成功");
            this.openSuccess = false;
            this.getList();
          }).finally(f => {
            this.btnLoading = false
          });
      } else {
        this.$message.error("请选择生产完成商品！")
      }
    },
    // 是否可以选择
    handelTableIsSelect(row, index){
      if (this.ids.length>0) {
        if (!this.successFlag){
          let suc = row.successRate.split('/')
          return parseInt(suc[0]) < parseInt(suc[1])
        }
      } else {
        return row.status === '0' || row.status === '1'
      }
    },
    // 查看采购商品
    handleLook(row){
      this.fileList = []
      this.payFileList = []
      const orderCode = row.orderCode
      this.orderCode = orderCode
      getPurchaseOrderInfo(orderCode).then(response => {
        let data = response.data;
        this.orderProductTable = data.products
        let accessoryList = data.accessoryList
        let payAccessoryList = data.payAccessoryList

        if (accessoryList && accessoryList.length > 0) {
          accessoryList.forEach(item => {
            let urls = item.split("/")
            this.fileList.push({name: urls[urls.length - 1], url: this.prefix + item})
          })
        }
        if (payAccessoryList && payAccessoryList.length > 0) {
          payAccessoryList.forEach(item => {
            let urls = item.split("/")
            this.payFileList.push({name: urls[urls.length - 1], url: this.prefix + item})
          })
        }

        this.openLook = true
      });
    },
    // 文件点击事件
    handlePreview(file){
      window.open(file.url,'_blank');
    },
    // 生产完成/发货选择商品
    handleContractSelectionChange(selection) {
      this.selectedProducts = selection
      this.formLogistics.productNum = selection.length
    },
    // 生产完成商品是否可以选择
    handelSuccessProductIsSelect(row, index){
      return row.status === '1'
    },
  }
};
</script>
<style scoped>
/deep/ .el-form-item--medium .el-form-item__content{
  line-height: 32px !important;
}
/deep/ .el-select {
  width: 100%;
}
</style>
